package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.pojo.Account;
import com.example.demo.pojo.User;
import com.example.demo.result.Result;
import com.example.demo.service.AccountService;
import com.example.demo.service.StudentService;
import com.example.demo.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/*
注册
 */
@RestController
@RequestMapping("/student")
public class StudentController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("register")
    public Result register(@RequestBody Account account){
        //先去数据库查找
        QueryWrapper<Account>qw=new QueryWrapper<>();
        qw.eq("username",account.getUsername());
        Account account1 = accountService.getBaseMapper().selectOne(qw);
        if(account1!=null){//用户已存在
            return Result.fail(20001,"用户已存在，请重新注册");
        }else{//用户不存在
            boolean save = accountService.save(account);
            if(save){
                return Result.success();
            }
        }
        return Result.fail();
    }

    //展示用户信息
    @PostMapping("getCurrentUser")
    public Result getCurrentUser(@RequestHeader("X-Token") String token){//当前用户从token里拿到，没有参数
        Account account=jwtUtil.parseToken(token,Account.class);//从token里得到用户
        Account currentUser = accountService.getById(account.getId());
        return Result.success(currentUser);
    }

    //修改用户信息
    @PostMapping("updateAccount")
    public Result updateAccount(@RequestBody Account account){
        boolean b = accountService.updateById(account);
        if(b){
            return Result.success();
        }else{
            return Result.fail();
        }
    }
}
